package com.yx.fx.log.web.config;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.ObjectUtil;
import com.yx.fx.log.db.entity.Logger;
import com.yx.fx.log.db.service.LoggerService;
import com.yx.fx.log.web.model.save.SaveLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨智杰
 * @date 2021/8/16 8:37
 */
@Slf4j
@Component
@EnableScheduling
public class LogCacheConfig {

    /**
     * 日志缓存,有效期一天
     */
    public static TimedCache<String, SaveLogger> logCache = CacheUtil.newTimedCache(DateUnit.DAY.getMillis());

    @Resource
    private LoggerService loggerService;

    /**
     * 定时任务,将缓存数据落库
     */
    @Scheduled(cron = "${web-log-config.db-save-cron:0 */10 * * * ?}")
    public void dbSave() {
        if (CollUtil.isNotEmpty(logCache.keySet())) {
            log.info("-------------------------日志缓存入库-------------------------");
            List<String> kList = new ArrayList<>();
            for (String k : logCache.keySet()) {
                loggerService.save(Convert.convert(Logger.class, logCache.get(k)));
                kList.add(ObjectUtil.clone(k));
            }
            kList.forEach(k -> logCache.remove(k));
            log.info("-------------------------本次保存了" + kList.size() + "条日志-------------------------");
        }
    }
}
